import json
import os
import os.path

class DB:
    def __init__(self):
        self.books_short_info = []    # [{book_name, book_id, lessons_type:[[id, name]...]} ...]
        self.books_data = {}    # {dir_name: book_info}
        # 遍历data目录，获取所有的book信息和数据
        data_path = os.path.abspath('../data')
        file_names = os.listdir(data_path)
        for name in file_names:
            book_dir_name = os.path.join(data_path, name)
            if os.path.isdir(book_dir_name) == False:
                continue
            if os.path.exists(os.path.join(book_dir_name, 'book_info.json')) == False:
                continue
            self._get_book_info(book_dir_name)
        self.books_short_info.sort(key = lambda x : x['book_id'])

    def _get_book_info(self, book_dir_name):
        '''读取book目录的内容，更新self.books_short_info和self.books_data'''
        short_info = {}
        book_info = {}
        book_dir_base_name = os.path.basename(book_dir_name)
        with open(os.path.join(book_dir_name, 'book_info.json'), encoding='UTF-8') as f:
            book_info_content = f.read()
            book_info = json.loads(book_info_content)
        short_info['book_id'] = book_dir_base_name
        short_info['book_name'] = book_info['book_name']
        if 'word_list' in book_info and 'word_data_file' in book_info:
            short_info['words'] = []
            for lesson_id, lesson_info in book_info['word_list'].items():
                short_info['words'].append([lesson_id, lesson_info[0]])
            short_info['words'].sort(key = lambda x : x[0])
            word_data = self._load_word_data_file(os.path.join(book_dir_name, book_info['word_data_file']))
            book_info['word_data'] = word_data
        if 'sentense_list' in book_info and 'sentense_data_file' in book_info:
            short_info['sentenses'] = []
            for lesson_id, lesson_info in book_info['sentense_list'].items():
                short_info['sentenses'].append([lesson_id, lesson_info[0]])
            short_info['sentenses'].sort(key = lambda x : x[0])
            # 暂时用_load_word_data_file加载例句数据
            sentense_data = self._load_word_data_file(os.path.join(book_dir_name, book_info['sentense_data_file']))
            book_info['sentense_data'] = sentense_data
        if 'gramma_list' in book_info and 'gramma_data_file' in book_info:
            short_info['grammas'] = []
            for lesson_id, lesson_info in book_info['gramma_list'].items():
                short_info['grammas'].append([lesson_id, lesson_info[0]])
            short_info['grammas'].sort(key = lambda x : x[0])
            # 暂时用_load_word_data_file加载语法数据
            gramma_data = self._load_word_data_file(os.path.join(book_dir_name, book_info['gramma_data_file']))
            book_info['gramma_data'] = gramma_data
        self.books_short_info.append(short_info)
        self.books_data[book_dir_base_name] = book_info

    def _load_word_data_file(self, file_name):
        '''读取word_data文件，返回一个字典{id:[]}
        []中内容依次为：id, w, g, pn, m, t, e, h, mp'''
        word_data = {}
        with open(file_name, encoding='UTF-8') as f:
            while True:
                line = f.readline()
                if line == '':
                    break
                line = line.strip()
                if line == '':  # 跳过空行
                    continue
                if line[0] == '#': # 跳过整行注释
                    continue
                word_info = line.split('`')
                word_info = list(map(lambda x : x.strip(), word_info))
                wim = {'id':0, 'w':'', 'g':'', 'pn':'', 'm':'', 't':'', 'e':'', 'h':'', 'mp':''} # word info map
                for item in word_info:
                    if item.strip() == '':
                        continue
                    kv = item.split('=')
                    if len(kv) != 2:
                        wim['id'] = int(item)
                    else:
                        wim[kv[0]] = kv[1]
                word_info = [wim['id'], wim['w'], wim['g'], wim['pn'], wim['m'], wim['t'], wim['e'], wim['h'], wim['mp']]
                if word_info[0] in word_data:
                    print('word_id %d repeated!'%(word_info[0]))
                    exit(1)
                word_data[word_info[0]] = word_info
        return word_data

    def get_books_short_info(self) -> list:
        return self.books_short_info

    def get_lesson_content(self, book_id, lesson_type, lesson_id) -> list:
        '''获取课程的内容列表，成功返回列表，否则返回None'''
        ret = []
        if lesson_type == 'words':
            ids = self.books_data[book_id]['word_list'][lesson_id][1]
            for id in ids:
                ret.append(self.books_data[book_id]['word_data'][id])
            return ret
        if lesson_type == 'sentenses':
            ids = self.books_data[book_id]['sentense_list'][lesson_id][1]
            for id in ids:
                ret.append(self.books_data[book_id]['sentense_data'][id])
            return ret
        if lesson_type == 'grammas':
            ids = self.books_data[book_id]['gramma_list'][lesson_id][1]
            for id in ids:
                ret.append(self.books_data[book_id]['gramma_data'][id])
            return ret
        return None
        